import CryptoJS from "crypto-js";

import { APPID, API_SECRET, API_KEY } from "@/utils/APIKEY";

let httpUrl = new URL("https://spark-api.xf-yun.com/v4.0/chat");
let modelDomain; // V1.1-V3.5动态获取，高于以上版本手动指定

var total_res = "";
let disabled = ref(false);
let text = ref([]);
let list = ref([
  {
    left: false,
    message: "可以聊天了~",
  },
]);

let bigModel = ref({});
// // 控制对话框的关闭
let ttsWSRef = ref({});

function getWebsocketUrl() {
  // console.log(httpUrl.pathname)
  // 动态获取domain信息
  switch (httpUrl.pathname) {
    case "/v1.1/chat":
      modelDomain = "general";
      break;
    case "/v2.1/chat":
      modelDomain = "generalv2";
      break;
    case "/v3.1/chat":
      modelDomain = "generalv3";
      break;
    case "/v3.5/chat":
      modelDomain = "generalv3.5";
      break;
    case "/v4.0/chat":
      modelDomain = "4.0Ultra";
      break;
  }

  return new Promise((resolve, reject) => {
    var apiKey = API_KEY;
    var apiSecret = API_SECRET;

    var url = "wss://" + httpUrl.host + httpUrl.pathname;

    // console.log("我打印的" + httpUrl.host)
    // console.log("我打印的" + httpUrl.pathname)

    var host = location.host;
    var date = new Date().toGMTString();
    var algorithm = "hmac-sha256";
    var headers = "host date request-line";
    var signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${httpUrl.pathname} HTTP/1.1`;
    var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
    var signature = CryptoJS.enc.Base64.stringify(signatureSha);
    var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
    var authorization = btoa(authorizationOrigin);
    url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
    resolve(url);
  });
}

// 聊天框滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    const chat = document.querySelector("#chat-message");
    //   console.log(chat.scrollHeight);
    chat.scrollTop = chat.scrollHeight;
    window.scroll(0, chat.scrollHeight + 50);
  });
};

const btnIsDisabled = () => {
  disabled.value = false;

  list.value[list.value.length - 1].tips = false;
};


const stopAnswer = () => {
    ttsWSRef.value.close()
    // 隐藏
    btnIsDisabled()
}


export const chatHooks = () => {


  onMounted(() => {
    class TTSRecorder {
      constructor({ appId = APPID } = {}) {
        this.appId = appId;
        this.status = "init";
      }

      // 修改状态
      setStatus(status) {
        this.onWillStatusChange && this.onWillStatusChange(this.status, status);
        this.status = status;
      }

      // 连接websocket  inpMessage 文本框的值
      connectWebSocket(inpMessage) {
        this.setStatus("ttsing");
        return getWebsocketUrl().then((url) => {
          let ttsWS;
          if ("WebSocket" in window) {
            ttsWS = new WebSocket(url);
          } else if ("MozWebSocket" in window) {
            ttsWS = new MozWebSocket(url);
          } else {
            alert("浏览器不支持WebSocket");
            return;
          }
          this.ttsWS = ttsWS;
          ttsWSRef.value = ttsWS;
          ttsWS.onopen = (e) => {
            // 文本框的值
            this.webSocketSend(inpMessage);
          };
          ttsWS.onmessage = (e) => {
            // console.log(e.data,'==onmessage==')
            this.result(e.data);
          };
          ttsWS.onerror = (e) => {
            clearTimeout(this.playTimeout);
            this.setStatus("error");
            alert("WebSocket报错，请f12查看详情");
            console.error(
              `详情查看：${encodeURI(url.replace("wss:", "https:"))}`
            );
          };
          ttsWS.onclose = (e) => {
            console.log(e);
          };
        });
      }

      // websocket发送数据
      webSocketSend(inpMessage) {
        var params = {
          header: {
            app_id: this.appId,
            uid: "fd3f47e4-d",
          },
          parameter: {
            chat: {
              domain: modelDomain,
              temperature: 0.5,
              max_tokens: 1024,
            },
          },
          payload: {
            message: {
              text: text.value,
            },
          },
        };

        this.ttsWS.send(JSON.stringify(params));
      }

      start(message) {
        total_res = ""; // 请空回答历史
        this.connectWebSocket(message);
      }

      // websocket接收数据的处理
      result(resultData) {
        let jsonData = JSON.parse(resultData);
        console.log(jsonData);
        let content = jsonData.payload?.choices?.text[0].content;
        console.log(jsonData.payload?.choices?.text[0].content);
        total_res += content;
        // xfa-1: 注释
        // $("#output_text").val(total_res);
        // console.log(resultData)
        // 提问失败

        list.value[list.value.length - 1].message += content;
        scrollToBottom();
        if (jsonData.header.code !== 0) {
          btnIsDisabled();
          alert(`提问失败: ${jsonData.header.code}:${jsonData.header.message}`);
          console.error(`${jsonData.header.code}:${jsonData.header.message}`);
          return;
        }
        if (jsonData.header.code === 0 && jsonData.header.status === 2) {
          text.value.push({
            role: "system",
            content: this.message,
          });

          btnIsDisabled();
          this.ttsWS.close();
          bigModel.value.setStatus("init");
        }
      }
    }

    bigModel.value = new TTSRecorder();

    bigModel.value.onWillStatusChange = function (oldStatus, status) {
      console.log(`output->oldStatus, status`, oldStatus, status);
    };
  });

  return {
    text,
    list,
    scrollToBottom,
    disabled,
    stopAnswer,
    bigModel
  };
};
